from django.shortcuts import render
from django.shortcuts import redirect
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from datetime import datetime
import hashlib
from django.core.paginator import Paginator
from common.models import Users,Types,Goods

# 商品导航信息加载
def loadPNav(request):
    '''商品导航信息加载'''
    context={}
    plists=Types.objects.filter(pid=0)
    print(plists)
    context["typelist"]=plists
    return context

def index(request):
    '''浏览购物车'''
    context=loadPNav(request)
    if "shoplist" not in request.session:
        request.session["shoplist"]={}
    return render(request,'web/cart.html',context)

def add(request,gid):
    '''加入购物车'''
    goods=Goods.objects.get(id=gid)
    shop=goods.toDict()
    shop["m"]=int(request.POST.get("m",1))#购买数量
    # 从购物车中获取商品列表
    shoplist=request.session.get("shoplist",{})
    # 判断商品是否在购物车中
    if gid in shoplist:# 已有商品，增加数量
        shoplist[gid]["m"]+=shop["m"]
    else:
        shoplist[gid]=shop # 购物车添加新商品
    # 购物车商品信息放回session
    request.session["shoplist"]=shoplist
    return redirect(reverse("cart_index"))

def delete(request,gid):
    '''从购物车中删除商品'''
    shoplist=request.session["shoplist"]
    del shoplist[gid]
    request.session["shoplist"]=shoplist
    return redirect(reverse("cart_index"))

def clear(request):
    '''清空购物车'''
    request.session["shoplist"]={}
    return redirect(reverse("cart_index"))

def change(request):
    '''修改购物车数量'''
    shoplist=request.session["shoplist"]
    # 获取修改商品id和数量
    gid=request.GET.get("gid","0")
    num=int(request.GET.get("num"))
    if num<1:
        num=1
    shoplist[gid]["m"]=num
    request.session["shoplist"]=shoplist
    return redirect(reverse("cart_index"))